import '../scss/detail.scss'

import Header from '../components/header'
import NewsFrame from '../components/news_frame'
import Collector from '../components/collector'

import tools from '../utils/tools'

const header = new Header(),
      newsFrame = new NewsFrame(),
      collector = new Collector();

const App = ($, win) => {
  const $app = $('#app'),
        $frameWrapper = $app.children('.frame-wrapper'),
        target = JSON.parse(localStorage.getItem('target')),
        newsUrl = tools.getUrlQueryValue('news_url') || target.news_url,
        uniquekey = tools.getUrlQueryValue('uniquekey') || target.uniquekey;

  let collections = JSON.parse(localStorage.getItem('collections')) || {},
      collected = Boolean(collections[uniquekey]); // 检测是否存在当前对象
  
  const init = () => {
    render();
  };

  const render = () => {
    _renderHeader();
    _renderNewsFrame(newsUrl);
    _renderCollector(collected);
    bindEven();
  };

  const bindEven = () => {
    $('.collector').on('click', newsCollect)
  }

  const _renderHeader = () => {
    $app.append(header.tpl({
      title: '新闻详情',
      showLeftIcon: true,
      showRightIcon: false
    }))
  };

  const _renderNewsFrame = (newsUrl) => {
    $frameWrapper.append(newsFrame.tpl(newsUrl));
  }

  const _renderCollector = (collected) => {
    $app.append(collector.tpl(collected));
  }

  function newsCollect () {
    // 1.未收藏,把数据保存到localSrorage中,{key: {}}
    // 2.已收藏,把数据从localSrorage移除
    if (collections[uniquekey]) {
      delete collections[uniquekey];
      collected = false;
    } else {
      collections[uniquekey] = JSON.parse(localStorage.getItem('target'));
      collected = true;
    }

    localStorage.setItem('collections', JSON.stringify(collections));
    collector.changeCollector(collected);
  }

  init();
}

App(Zepto, window);